package com.example.sunmiv1.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.sunmiv1.R;
import com.example.sunmiv1.activity.AddGoodsActivity;
import com.example.sunmiv1.activity.ChooseActivity;
import com.example.sunmiv1.activity.CollectRecordActivity;
import com.example.sunmiv1.activity.CollectingSilverActivity;
import com.example.sunmiv1.activity.CreditActivity;
import com.example.sunmiv1.activity.DeliveryGoodsActivity;
import com.example.sunmiv1.activity.FlowManageActivity;
import com.example.sunmiv1.activity.GoodsSaleListActivity;
import com.example.sunmiv1.activity.HangOverActivity;
import com.example.sunmiv1.activity.IndexDetailsActivity;
import com.example.sunmiv1.activity.InventoryManageActivity;
import com.example.sunmiv1.activity.LoginActivity;
import com.example.sunmiv1.activity.OnlineOrderActivity;
import com.example.sunmiv1.activity.PriceQueryActivity;
import com.example.sunmiv1.activity.PurchaseManageActivity;
import com.example.sunmiv1.activity.StockInquiryActivity;
import com.example.sunmiv1.activity.StoreOrderActivity;
import com.example.sunmiv1.activity.VipIndexActivity;
import com.example.sunmiv1.activity.good.GoodsManageActivity;
import com.example.sunmiv1.adapter.IndexPageAdapter;
import com.example.sunmiv1.entity.IndexPageBean;
import com.example.sunmiv1.entity.LoginEntity;
import com.example.sunmiv1.entity.SellcountBean;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class IndexFragment extends Fragment {

    @BindView(R.id.index_name)
    TextView indexName;
    @BindView(R.id.index_shopName)
    TextView indexShopName;
    @BindView(R.id.index_details)
    TextView indexDetails;
    @BindView(R.id.index_turnover)
    TextView indexTurnover;
    @BindView(R.id.index_collectingNum)
    TextView indexCollectingNum;
    Unbinder unbinder;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.index_gridView)
    GridView indexGridView;
    @BindView(R.id.index_spinner)
    Spinner indexSpinner;
    @BindView(R.id.index_signOut)
    TextView indexSignOut;
    private View view;
    private ACache aCache;
    private Intent intent;
    private Context context;
    private List<IndexPageBean> imgList;
    private SellcountBean sellcountBean;
    private IndexPageAdapter indexpageAdapter;
    private List<String> storeList;
    private JSONArray jsonArray;
    private AlertDialog alertDialog;
    private LoginEntity loginEntity;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (getActivity() == null || getActivity().getWindow().getWindowManager() == null) {
                        return;
                    }
                    indexTurnover.setText(sellcountBean.getInfo().getAllmoney() + "");
                    indexCollectingNum.setText(sellcountBean.getInfo().getCount() + "");
                    setIndex();
                    break;
                case 2:
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.index_fragment, null);
        context = getActivity();
        aCache = ACache.get(context);
        unbinder = ButterKnife.bind(this, view);
        imgList = new ArrayList<>();
        storeList = new ArrayList<>();
        sp = context.getSharedPreferences("context", Activity.MODE_PRIVATE);//創建sp對象
        initData();
        return view;
    }

    /*門店適配器*/
    private void setStoreAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, storeList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drop);
        indexSpinner.setAdapter(arrayAdapter);
    }

    private void initData() {
        addPurchaseOrderBasics();
        indexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                try {
                    aCache.put("storeid", jsonArray.getJSONObject(position).getString("storeid"));
                    aCache.put("storetag", storeList.get(position));
                    if (!indexShopName.getText().toString().trim().equals(storeList.get(position))) {
                        getSellcount();
                    }
                    indexShopName.setText(storeList.get(position));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        indexGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (imgList.get(position).getImg()) {
                    case R.mipmap.index_business_data://營業數據
                        intent = new Intent(context, IndexDetailsActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.index_vip://會員
                        intent = new Intent(context, VipIndexActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.index_add_goods://新增商品
                        intent = new Intent(context, AddGoodsActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.index_inventory://庫存管理
                        intent = new Intent(context, InventoryManageActivity.class);
                        startActivity(intent);
                        break;
//                    case R.mipmap.index_report_loss://進貨
//                        intent = new Intent(context, ReportLossActivity.class);
//                        startActivity(intent);
//                        break;
                    case R.mipmap.index_collecting_silver://收銀
                        intent = new Intent(context, CollectingSilverActivity.class);
                        intent.putExtra("flag", 1);
                        startActivity(intent);
                        break;
                    case R.mipmap.index_online_order://線上訂單
                        intent = new Intent(context, OnlineOrderActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.nav_kc: //庫存查詢
                        intent = new Intent(context, StockInquiryActivity.class);
                        intent.putExtra("search", "1");
                        startActivity(intent);
                        break;
                    case R.mipmap.nav_price: //商品價格
                        intent = new Intent(context, PriceQueryActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.quick_collect://快速收款
                        intent = new Intent(context, ChooseActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.index_collect://快速收款列表
                        intent = new Intent(context, CollectRecordActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.goods_sale_list://商品銷售列表
                        intent = new Intent(context, GoodsSaleListActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.store_order:// 訂單明細
                        intent = new Intent(context, StoreOrderActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.good_warehousing://貨流管理
                        intent = new Intent(context, FlowManageActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.index_deposit://採購管理
                        intent = new Intent(context, PurchaseManageActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.index_hang_over://交班數據
                        intent = new Intent(context, HangOverActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.index_credit://賒賬
                        intent = new Intent(context, CreditActivity.class);
                        startActivity(intent);
                        break;
                    case R.mipmap.new_good_manage://商品管理
                        GoodsManageActivity.intent(sellcountBean,context);
//                        intent = new Intent(context, GoodsManageActivity.class);
//                        startActivity(intent);
                        break;
                }
            }
        });
    }

    private void setIndexPageAdapter() {
        indexpageAdapter = new IndexPageAdapter(context, imgList);
        indexGridView.setAdapter(indexpageAdapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        getSellcount();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void getSellcount() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            HttpUtils.post(context, Common.GET_SELL_COUNT, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    sellcountBean = GsonUtils.JsonToBean(text, SellcountBean.class);
                    Message msg = new Message();
                    if (sellcountBean.getStatus() == 1) {
                        if (aCache.getAsString("userType").equals("2") || aCache.getAsString("userType").equals("3")) {
                            aCache.put("showPrice", sellcountBean.getJurisdiction().getShowpurch_price());//  查看進價
                            aCache.put("allocation", sellcountBean.getJurisdiction().getAllocation());//  門店之間調撥審覈
                        }
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
private boolean isFrist=true;
    private void setIndex(){
        if ("1".equals(aCache.getAsString("userType"))) {//商家
            indexSpinner.setVisibility(View.VISIBLE);
            indexName.setVisibility(View.GONE);
            if (isFrist) {
                jsonArray = aCache.getAsJSONArray("storelist");
                Gson gson=new Gson();
                Log.d("店鋪列表",gson.toJson(jsonArray));
                try {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        storeList.add(jsonArray.getJSONObject(i).getString("name"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                setStoreAdapter();
                indexName.setText(aCache.getAsString("storeTag"));
                indexShopName.setText(aCache.getAsString("storeTag"));
                isFrist=false;
            }else {
                indexName.setText(aCache.getAsString("storetag"));
                indexShopName.setText(aCache.getAsString("storetag"));
            }
            imgList.clear();
            imgList.add(new IndexPageBean(R.mipmap.index_business_data, R.string.index_businessData));//營業數據
            imgList.add(new IndexPageBean(R.mipmap.index_vip, R.string.index_vip));//會員
//            imgList.add(new IndexPageBean(R.mipmap.index_add_goods, R.string.index_addGoods));//新增商品
            if ("1".equals(aCache.getAsString("platform_type"))) {
                imgList.add(new IndexPageBean(R.mipmap.index_inventory, R.string.index_inventory));//盤點
            }
//            imgList.add(new IndexPageBean(R.mipmap.index_collect, R.string.index_collectRecord));//快速收款列表
            if ("1".equals(aCache.getAsString("platform_type"))) {
                imgList.add(new IndexPageBean(R.mipmap.good_warehousing, R.string.good_warehousing));//貨流管理
            }
            if ("1".equals(aCache.getAsString("platform_type"))) {
                imgList.add(new IndexPageBean(R.mipmap.index_deposit, R.string.index_deposit));//出庫單
            }
            if ("1".equals(aCache.getAsString("credit"))) {
                imgList.add(new IndexPageBean(R.mipmap.index_credit, R.string.index_credit));//賒賬
            }
            imgList.add(new IndexPageBean(R.mipmap.new_good_manage, R.string.new_good_manage));//商品管理
            setIndexPageAdapter();
        } else if ("2".equals(aCache.getAsString("userType"))) {//店長
            indexSpinner.setVisibility(View.GONE);
            indexName.setVisibility(View.VISIBLE);
            indexName.setText(aCache.getAsString("storeTag"));
            indexShopName.setText(aCache.getAsString("storeTag"));
            imgList.clear();
            imgList.add(new IndexPageBean(R.mipmap.index_business_data, R.string.index_businessData));//營業數據
            imgList.add(new IndexPageBean(R.mipmap.index_vip, R.string.index_vip));//會員
//            imgList.add(new IndexPageBean(R.mipmap.index_add_goods, R.string.index_addGoods));//新增商品
            if ("1".equals(aCache.getAsString("platform_type"))) {
                imgList.add(new IndexPageBean(R.mipmap.index_inventory, R.string.index_inventory));//盤點
            }
            if ("1".equals(aCache.getAsString("platform_type"))) {
                imgList.add(new IndexPageBean(R.mipmap.nav_kc, R.string.store_query)); //庫存查詢
            }
            imgList.add(new IndexPageBean(R.mipmap.nav_price, R.string.goods_price)); // 商品價格
            imgList.add(new IndexPageBean(R.mipmap.quick_collect, R.string.index_collect));//快速收款
            imgList.add(new IndexPageBean(R.mipmap.goods_sale_list, R.string.index_goodsSaleList));//商品銷售明細列表
            imgList.add(new IndexPageBean(R.mipmap.store_order, R.string.index_storeOrder));//訂單明細
            if ("1".equals(aCache.getAsString("platform_type"))) {
                if (!"2".equals(aCache.getAsString("supplier_type")))
                    imgList.add(new IndexPageBean(R.mipmap.good_warehousing, R.string.good_warehousing));//貨流管理
                imgList.add(new IndexPageBean(R.mipmap.index_deposit, R.string.index_deposit));//採購管理
            }
            if ("1".equals(aCache.getAsString("credit"))) {
                imgList.add(new IndexPageBean(R.mipmap.index_credit, R.string.index_credit));//賒賬
            }
                imgList.add(new IndexPageBean(R.mipmap.new_good_manage, R.string.new_good_manage));//商品管理
            setIndexPageAdapter();
        } else {//員工
            Gson gson=new Gson();
            LoginEntity loginEntity = gson.fromJson(aCache.getAsString("loginInfo"), LoginEntity.class);
            indexSpinner.setVisibility(View.GONE);
            indexName.setVisibility(View.VISIBLE);
            indexName.setText(aCache.getAsString("storeTag"));
            indexShopName.setText(aCache.getAsString("storeTag"));
            imgList.clear();
            imgList.add(new IndexPageBean(R.mipmap.index_business_data, R.string.index_businessData));//營業數據
            imgList.add(new IndexPageBean(R.mipmap.index_vip, R.string.index_vip));//會員
            if ("1".equals(aCache.getAsString("platform_type"))) {
                imgList.add(new IndexPageBean(R.mipmap.index_inventory, R.string.index_inventory));//盤點
            }
            imgList.add(new IndexPageBean(R.mipmap.index_collecting_silver, R.string.index_collectingSilver));//收銀
            imgList.add(new IndexPageBean(R.mipmap.index_online_order, R.string.index_onlineOrder));//線上訂單
            imgList.add(new IndexPageBean(R.mipmap.quick_collect, R.string.index_collect));//快速收款
            imgList.add(new IndexPageBean(R.mipmap.index_hang_over, R.string.index_hangOver));//交班數據
            if ("1".equals(aCache.getAsString("credit"))) {
                imgList.add(new IndexPageBean(R.mipmap.index_credit, R.string.index_credit));//賒賬
            }
            if (loginEntity.getData().getAuth().getIs_goods_manage()==1) {
                imgList.add(new IndexPageBean(R.mipmap.new_good_manage, R.string.new_good_manage));//商品管理
            }
            setIndexPageAdapter();
        }
    }

    /**
     * 採購修改售價權限
     */
    private void addPurchaseOrderBasics() {
        HttpUtils.post(context, Common.ADD_PURCHASE_ORDER_BASICS, Tools.createParameterCode(new JSONObject()), new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                try {
                    JSONObject json = new JSONObject(text);
                    if (json.getInt("status") == 1) {
                        JSONObject data = json.getJSONObject("data");
                        //1關閉 2開啓
                        aCache.put("modify_price_state", data.getString("modify_price_state"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    @OnClick({R.id.index_details, R.id.index_signOut})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.index_details://詳情
                intent = new Intent(context, IndexDetailsActivity.class);
                startActivity(intent);
                break;
            case R.id.index_signOut:
                creatDialog();
                if (alertDialog != null) {
                    alertDialog.show();
                }
                break;
        }
    }

    private SharedPreferences sp;

    private void creatDialog() {//type:1,保存；2,刪除
        //創建AlertDialog的構造器的對象
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        //設置構造器標題
        builder.setTitle(R.string.Tips);
        //構造器內容,爲對話框設置文本項(之後還有列表項的例子)
        builder.setMessage(R.string.quit);
        //爲構造器設置確定按鈕,第一個參數爲按鈕顯示的文本信息，第二個參數爲點擊後的監聽事件，用匿名內部類實現
        builder.setPositiveButton(R.string.refund_confirm, (dialog, which) -> {
            //第一個參數dialog是點擊的確定按鈕所屬的Dialog對象,第二個參數which是按鈕的標示值
//                finish();//結束App
            String login_acnum = aCache.getAsString("login_acnum") == null ? "" : aCache.getAsString("login_acnum");
            String login_pass = "";
            String login_ischeck = aCache.getAsString("login_ischeck") == null ? "" : aCache.getAsString("login_ischeck");
            String userType = aCache.getAsString("userType") == null ? "" : aCache.getAsString("userType");
            SharedPreferences.Editor editor = sp.edit();
            String url = aCache.getAsString("url");
            String logo=aCache.getAsString("logo");
            if (url == null || TextUtils.isEmpty(url)) {
                url = sp.getString("url", "");
            }
            if ("1".equals(login_ischeck)) {
                login_pass = aCache.getAsString("login_pass") == null ? "" : aCache.getAsString("login_pass");
            }
            aCache.clear();
            aCache.put("url", url);
            aCache.put("login_acnum", login_acnum);
            aCache.put("login_pass", login_pass);
            aCache.put("login_ischeck", login_ischeck);
            aCache.put("userType", userType);
            aCache.put("logo", logo);
            getActivity().finish();
            intent = new Intent(context, LoginActivity.class);
            startActivity(intent);
        });
        //爲構造器設置取消按鈕,若點擊按鈕後不需要做任何操作則直接爲第二個參數賦值null
        builder.setNegativeButton(R.string.inventory_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {


            }
        });
//        //爲構造器設置一個比較中性的按鈕，比如忽略、稍後提醒等
//        builder.setNeutralButton("稍後提醒",null);
        //利用構造器創建AlertDialog的對象,實現實例化
        alertDialog = builder.create();
    }
}
